<template>
    <div class="user-manage-container">
        <div class="sidebar">
            <el-input v-model="deptFilter" placeholder="搜索部门" clearable @input="filterDeptTree"
                class="dept-search-input" />
            <el-tree :data="deptTree" :props="treeProps" node-key="departmentId" :filter-node-method="filterDeptNode"
                @node-click="handleDeptClick" ref="deptTreeRef" highlight-current class="dept-tree" />
        </div>
        <div class="main-content">
            <!-- 查询条件 -->
            <el-form :inline="true" :model="searchForm" class="user-filter">
                <el-form-item label="用户名">
                    <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable style="width: 200px" />
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="searchForm.userPhone" placeholder="请输入手机号" clearable style="width: 200px" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.userStatus" placeholder="全部" clearable style="width: 120px">
                        <el-option label="正常" :value="0" />
                        <el-option label="停用" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker v-model="searchForm.registerTime" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" style="width: 300px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchUserList">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- 按钮组 -->
            <div class="user-actions">
                <el-button type="success" @click="openAddDialog">新增</el-button>
                <el-button type="danger" :disabled="selectedUsers.length === 0"
                    @click="confirmBatchDelete">批量删除</el-button>
                <el-button type="warning" :disabled="userList.length === 0" @click="exportToExcel">导出Excel</el-button>
            </div>
            <!-- 用户表格 -->
            <el-table :data="userList" border stripe style="width: 100%; margin-top: 10px;" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="userId" label="用户编号" min-width="80" />
                <el-table-column prop="userName" label="用户名" min-width="120" />
                <el-table-column prop="userNickname" label="用户昵称" min-width="120" />
                <el-table-column label="部门" min-width="120">
                    <template #default="{ row }">
                        {{ getDeptName(row.departmentId) }}
                    </template>
                </el-table-column>
                <el-table-column prop="userPhone" label="手机号" min-width="120" />
                <el-table-column prop="userStatus" label="状态" min-width="80">
                    <template #default="{ row }">
                        <el-switch v-model="row.userStatus" :active-value="0" :inactive-value="1"
                            @change="val => handleStatusChange(row, val)" />
                    </template>
                </el-table-column>
                <el-table-column prop="registerTime" label="创建时间" min-width="160" />
                <el-table-column label="操作" min-width="160">
                    <template #default="{ row }">
                        <el-button size="small" @click="openEditDialog(row)">修改</el-button>
                        <el-button size="small" type="danger" @click="confirmDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
                :total="pagination.total" @current-change="fetchUserList" @size-change="fetchUserList"
                layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50]"
                style="margin-top: 16px; text-align: right;" />
        </div>
        <!-- 新增/编辑弹窗 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="用户名" prop="userName" v-if="!form.userId">
                            <el-input v-model="form.userName" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="userPhone">
                            <el-input v-model="form.userPhone" />
                        </el-form-item>
                        <el-form-item label="性别" prop="gender">
                            <el-select v-model="form.gender" placeholder="请选择性别">
                                <el-option v-for="item in genderOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="岗位" prop="positionId">
                            <el-select v-model="form.positionId" placeholder="请选择岗位">
                                <el-option v-for="item in positionList" :key="item.positionId"
                                    :label="item.positionName" :value="item.positionId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用户昵称" prop="userNickname">
                            <el-input v-model="form.userNickname" />
                        </el-form-item>
                        <el-form-item label="邮箱" prop="userEmail">
                            <el-input v-model="form.userEmail" />
                        </el-form-item>
                        <el-form-item label="部门" prop="departmentId">
                            <el-tree-select v-model="form.departmentId" :data="deptTree"
                                :props="{ label: 'departmentName', children: 'children', value: 'departmentId' }"
                                placeholder="请选择部门" check-strictly style="width: 100%;" clearable />
                        </el-form-item>
                        <el-form-item label="角色" prop="userType">
                            <el-select v-model="form.userType" placeholder="请选择角色">
                                <el-option :label="'普通用户'" :value="0" />
                                <el-option :label="'企业管理员'" :value="1" />
                                <el-option :label="'超级管理员'" :value="2" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="密码" prop="password" v-if="!form.userId">
                            <el-input v-model="form.password" type="password" show-password />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" :rows="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 删除确认弹窗 -->
        <el-dialog title="系统提示" v-model="deleteDialogVisible" width="350px">
            <span>是否确认删除该用户？</span>
            <template #footer>
                <el-button @click="deleteDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="deleteUser">确定</el-button>
            </template>
        </el-dialog>
        <!-- 错误提示弹窗 -->
        <el-dialog title="错误" v-model="errorDialogVisible" width="350px" show-close>
            <span>{{ errorMessage }}</span>
            <template #footer>
                <el-button type="primary" @click="errorDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import UserService from '../services/UserService';
import DepartmentService from '../services/DepartmentService';
import { ElMessage } from 'element-plus';

const deptTree = ref([]);
const flatDeptList = ref([]);
const deptFilter = ref('');
const deptTreeRef = ref();
const treeProps = { label: 'departmentName', children: 'children' };
const selectedDeptId = ref();

const userList = ref([]);
const loading = ref(false);
const pagination = reactive({ page: 1, size: 10, total: 0 });
const searchForm = reactive({
    userName: '',
    userPhone: '',
    userStatus: undefined,
    registerTime: [],
});

const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = reactive({
    userId: undefined,
    userName: '',
    userNickname: '',
    userPhone: '',
    userEmail: '',
    userStatus: 0,
    password: '',
    departmentId: undefined,
    gender: 1,
    positionId: undefined,
    userType: 0,
    remark: ''
});
const formRef = ref();
const rules = {
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名只能包含字母、数字、下划线和横杠', trigger: 'blur' }
    ],
    userNickname: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
        { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,20}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
    ],
    userPhone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    userEmail: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    departmentId: [
        { required: true, message: '请选择部门', trigger: 'change' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    positionId: [
        { required: true, message: '请选择岗位', trigger: 'change' }
    ],
    userType: [
        { required: true, message: '请选择角色', trigger: 'change' }
    ]
};
const deleteDialogVisible = ref(false);
const deleteRow = ref(null);
const errorDialogVisible = ref(false);
const errorMessage = ref('');
const selectedUsers = ref([]);

// 性别选项
const genderOptions = [
    { label: '男', value: 1 },
    { label: '女', value: 2 }
];

// 岗位列表
const positionList = ref([]);
// 角色列表
const roleList = ref([]);

function showError(msg) {
    errorMessage.value = msg;
    errorDialogVisible.value = true;
}

function filterDeptNode(value, data) {
    if (!value) return true;
    return data.departmentName && data.departmentName.indexOf(value) !== -1;
}
function filterDeptTree() {
    deptTreeRef.value && deptTreeRef.value.filter(deptFilter.value);
}
function handleDeptClick(node) {
    selectedDeptId.value = node.departmentId;
    // 递归获取所有子部门ID
    const getAllDeptIds = (deptNode) => {
        let ids = [deptNode.departmentId];
        if (deptNode.children && deptNode.children.length) {
            deptNode.children.forEach(child => {
                ids = ids.concat(getAllDeptIds(child));
            });
        }
        return ids;
    };
    const deptIds = getAllDeptIds(node);
    loading.value = true;
    UserService.getUserListByDepts(deptIds, pagination.page, pagination.size)
        .then(res => {
            if (res.code === 200) {
                userList.value = res.data.list || [];
                pagination.total = res.data.total;
                pagination.page = res.data.page;
                pagination.size = res.data.size;
            } else {
                showError(res.message || '获取用户列表失败');
            }
        })
        .catch(e => {
            showError(e.message || '获取用户列表失败');
        })
        .finally(() => {
            loading.value = false;
        });
}
function resetSearch() {
    searchForm.userName = '';
    searchForm.userPhone = '';
    searchForm.userStatus = undefined;
    searchForm.registerTime = [];
    pagination.page = 1;
    fetchUserList();
}
function openAddDialog() {
    dialogTitle.value = '新增用户';
    Object.assign(form, {
        userId: undefined,
        userName: '',
        userNickname: '',
        userPhone: '',
        userEmail: '',
        userStatus: 0,
        password: '',
        departmentId: undefined,
        gender: 1,
        positionId: undefined,
        userType: 0,
        remark: ''
    });
    dialogVisible.value = true;
    // 重置表单验证状态
    nextTick(() => {
        formRef.value?.resetFields();
    });
}
function openEditDialog(row) {
    dialogTitle.value = '修改用户';
    // 直接用 row 数据填充表单
    form.userId = row.userId;
    form.userName = row.userName;
    form.userNickname = row.userNickname;
    form.userPhone = row.userPhone;
    form.userEmail = row.userEmail;
    form.userStatus = row.userStatus;
    form.departmentId = row.departmentId;
    form.gender = row.gender;
    form.positionId = row.positionId;
    form.userType = row.userType;
    form.remark = row.remark;
    
    dialogVisible.value = true;
    // 重置表单验证状态
    nextTick(() => {
        formRef.value?.clearValidate(); // 替换 resetFields()
    });
}
function handleStatusChange(row, val) {
    row.userStatus = val === 0 ? 0 : 1;
    UserService.updateUser(row.userId, { userStatus: row.userStatus }).then(res => {
        if (res.code === 200) {
            ElMessage.success('修改状态成功');
            fetchUserList();
        } else {
            showError(res.message || '修改失败');
        }
    }).catch(e => {
        showError(e.message || '修改失败');
    });
}

function confirmDelete(row) {
    deleteRow.value = row;
    deleteDialogVisible.value = true;
}
function handleSelectionChange(selection) {
    selectedUsers.value = selection;
}

async function confirmBatchDelete() {
    if (selectedUsers.value.length === 0) {
        showError('请选择要删除的用户');
        return;
    }
    deleteRow.value = null; // 标记为批量删除
    deleteDialogVisible.value = true;
}

async function deleteUser() {
    if (deleteRow.value) {
        // 单个删除
        try {
            const res = await UserService.deleteUser(deleteRow.value.userId);
            if (res.code === 200) {
                deleteDialogVisible.value = false;
                fetchUserList();
            } else {
                showError(res.message || '删除失败');
            }
        } catch (e) {
            showError(e.message || '删除失败');
        }
    } else if (selectedUsers.value.length > 0) {
        // 批量删除
        try {
            let successCount = 0;
            for (const user of selectedUsers.value) {
                const res = await UserService.deleteUser(user.userId);
                if (res.code === 200) successCount++;
            }
            deleteDialogVisible.value = false;
            fetchUserList();
            if (successCount === selectedUsers.value.length) {
                // 全部成功
            } else {
                showError(`部分删除失败，成功删除${successCount}个用户`);
            }
        } catch (e) {
            showError(e.message || '批量删除失败');
        }
    }
}

function buildDeptTree(list) {
    const idMap = {};
    list.forEach(item => { idMap[item.departmentId] = { ...item, children: [] }; });
    const tree = [];
    list.forEach(item => {
        const node = idMap[item.departmentId];
        if (item.superiorId && idMap[item.superiorId]) {
            idMap[item.superiorId].children.push(node);
        } else {
            tree.push(node);
        }
    });
    return tree;
}
function getDeptName(deptId) {
    const dept = flatDeptList.value.find(d => d.departmentId === deptId);
    return dept ? dept.departmentName : '';
}

function flattenDeptTree(list) {
    const arr = [];
    function dfs(nodes) {
        nodes.forEach(node => {
            arr.push(node);
            if (node.children && node.children.length) dfs(node.children);
        });
    }
    dfs(list);
    return arr;
}
async function fetchDeptTree() {
    try {
        const res = await DepartmentService.getDepartmentListWithPage({});
        if (res.code === 200) {
            const deptList = res.data.list || [];
            deptTree.value = buildDeptTree(deptList);
            flatDeptList.value = flattenDeptTree(deptTree.value);
        }
    } catch { }
}
async function fetchUserList() {
    loading.value = true;
    try {
        const params = {
            page: pagination.page,
            size: pagination.size,
            userName: searchForm.userName,
            userPhone: searchForm.userPhone,
            userStatus: searchForm.userStatus,
        };
        if (selectedDeptId.value) {
            params.departmentId = selectedDeptId.value;
        }
        if (searchForm.registerTime && searchForm.registerTime.length === 2) {
            params.startTime = searchForm.registerTime[0];
            params.endTime = searchForm.registerTime[1];
        }
        console.log(params);
        const res = await UserService.getUserList(params);
        console.log(res);
        if (res.code === 200) {
            userList.value = res.data.list || [];
            pagination.total = res.data.total;
            pagination.page = res.data.page;
            pagination.size = res.data.size;
        } else {
            showError(res.message || '获取用户列表失败');
        }
    } catch (e) {
        showError(e.message || '获取用户列表失败');
    } finally {
        loading.value = false;
    }
}
function submitForm() {
    formRef.value.validate(async (valid) => {
        if (!valid) return;
        try {
            if (form.userId) {
                // 修改
                const updateData = {
                    userNickname: form.userNickname,
                    userEmail: form.userEmail,
                    userPhone: form.userPhone,
                    userStatus: form.userStatus,
                    departmentId: form.departmentId,
                    gender: form.gender,
                    positionId: form.positionId,
                    userType: form.userType,
                    remark: form.remark
                };
                const res = await UserService.updateUser(form.userId, updateData);
                console.log(res);
                if (res.code === 200) {
                    dialogVisible.value = false;
                    ElMessage.success('修改成功');
                    fetchUserList();
                } else {
                    showError(res.message || '修改失败');
                }
            } else {
                // 新增
                const addData = {
                    userName: form.userName,
                    userNickname: form.userNickname,
                    password: form.password,
                    userEmail: form.userEmail,
                    userPhone: form.userPhone,
                    userStatus: form.userStatus,
                    departmentId: form.departmentId,
                    gender: form.gender,
                    positionId: form.positionId,
                    userType: form.userType,
                    remark: form.remark
                };
                const res = await UserService.addUser(addData);
                if (res.code === 200) {
                    dialogVisible.value = false;
                    fetchUserList();
                } else {
                    showError(res.message || '创建失败');
                }
            }
        } catch (e) {
            showError(e.message || (form.userId ? '修改失败' : '创建失败'));
        }
    });
}

async function exportToExcel() {
    try {
        if (userList.value.length === 0) {
            showError('没有数据可导出');
            return;
        }
        const XLSX = await import('xlsx');
        const exportData = userList.value.map(user => ({
            '用户ID': user.userId,
            '用户名': user.userName,
            '用户昵称': user.userNickname,
            '手机号': user.userPhone,
            '邮箱': user.userEmail,
            '状态': user.userStatus === 0 ? '正常' : '停用',
            '注册时间': user.registerTime
        }));
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.json_to_sheet(exportData);
        worksheet['!cols'] = [
            { wch: 10 },
            { wch: 20 },
            { wch: 20 },
            { wch: 15 },
            { wch: 25 },
            { wch: 10 },
            { wch: 20 }
        ];
        XLSX.utils.book_append_sheet(workbook, worksheet, '用户列表');
        const fileName = `用户列表_${new Date().toISOString().split('T')[0]}.xlsx`;
        XLSX.writeFile(workbook, fileName);
    } catch (error) {
        showError('导出失败，请重试');
    }
}

function closeDialog() {
    dialogVisible.value = false;
    formRef.value?.resetFields();
}

// 获取岗位列表
async function fetchPositionList() {
    try {
        const res = await UserService.getPositionList();
        if (res.code === 200) {
            positionList.value = res.data || [];
            console.log(positionList.value);
        }
    } catch (error) {
        console.error('获取岗位列表失败:', error);
    }
}

// 获取角色列表
async function fetchRoleList() {
    try {
        const res = await UserService.getRoleList();
        if (res.code === 200) {
            roleList.value = res.data || [];
        }
    } catch (error) {
        console.error('获取角色列表失败:', error);
    }
}

onMounted(() => {
    UserService.loadCurrentUser();
    fetchDeptTree();
    fetchUserList();
    fetchPositionList();
    fetchRoleList();
});
</script>

<style scoped>
.user-manage-container {
    display: flex;
    height: 100vh;
    background: #fff;
}

.sidebar {
    width: 240px;
    background: #f7f8fa;
    border-right: 1px solid #e6e6e6;
    padding: 16px 8px 0 8px;
    display: flex;
    flex-direction: column;
}

.dept-search-input {
    margin-bottom: 8px;
}

.dept-tree {
    flex: 1;
    background: #fff;
    border-radius: 4px;
    padding: 8px 0;
}

.main-content {
    flex: 1;
    padding: 24px 32px 0 32px;
    overflow: auto;
}

.user-filter {
    margin-bottom: 10px;
}

.user-actions {
    margin-bottom: 10px;
}
</style>